package com.chat.http.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chat.constant.tab.CertificateConstant;
import com.chat.http.service.PlanConnectionService;
import com.chat.http.service.PushMoodService;
import com.chat.http.validator.OnlinePeopleVoValidator;
import com.chat.vo.params.OnlinePeopleVo;
import com.chat.websocket.online.OnlineManage;

@Controller
@RequestMapping("/mood")
public class PushMoodController {
	
	private Map<String, Object> map;
	
	@Autowired
	private PushMoodService moodService;
	
	@Autowired
	private OnlinePeopleVoValidator thisValidator;
	
	@Autowired
	private PlanConnectionService planConnectionService;
	/**
	 * http://119.29.146.227:8080/chat/mood/push?
	 * userName=xxx&token=xxx&
	 * accesskey=xxx&secretkey=xxx&
	 * headimg=xxx
	 * @param op
	 * @param mood
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/push")
	public Map<String, Object> pushMood(String accesskey, String secretkey,
			OnlinePeopleVo op,String headimg,BindingResult result) throws Exception{
		map = new HashMap<>();
		map.put("status", "error");
		thisValidator.planConnValidate(accesskey, secretkey, op, result);
		if (result.hasErrors()) {
			map.put("massage", result.getAllErrors().get(0).getCode());
			return map;
		} else {
			// 校对凭证信息
			boolean flag = planConnectionService.valiatorCertificate(CertificateConstant.TYPE_ADMIN.getValue(),
					accesskey, secretkey);
			if (!flag) {
				map.put("massage", "凭证错误");
				return map;
			}
			String userName = op.getUserName();
			String token = op.getToken();
			if (OnlineManage.isOnlined(userName)) {
			}else if (OnlineManage.isExistInPlanConnTemp(userName, token)) {
				OnlineManage.addToOnlineUserList(op);
				OnlineManage.removeInPlanConnTemp(userName, token);
				
			}else {
				return map;
			}
			//TODO 推送信息给好友
			moodService.pushFriends(userName,headimg);
			map.put("status", "success");
			return map;
		}
		
	}
}
